package net.cardgame.orcalecard;

import java.util.Arrays;
import java.util.Collection;
import java.util.List;

import jp.jma.oraclecard.R;
import net.cardgame.oraclecard.common.ThreadLoadImage;
import net.cardgame.orcalecard.bean.CardBean;
import net.cardgame.orcalecard.utils.ConstantValue;
import net.cardgame.orcalecard.utils.KeyboardHelper;
import net.cardgame.orcalecard.utils.NetworkUtils;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.LoggingBehavior;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.Session.StatusCallback;
import com.facebook.SessionLoginBehavior;
import com.facebook.SessionState;
import com.facebook.Settings;

public class PostFacebookActivity extends Activity implements OnClickListener {

	ImageView card1;
	ImageView card2;
	ImageView card3;
	ImageView card4;
	ImageView jumpCard;
	ImageView btn_share;
	ImageView bg_layout;
	LinearLayout wait_layout;
	ImageView btn_back;
	ImageView btn_help;
	EditText edit_status;
	CardBean cardBean1;
	CardBean cardBean2;
	CardBean cardBean3;
	CardBean cardBean4;
	Bitmap postBitmap = null;
	int number_of_card;
	int deckId;
	// phiên kết nối facebook
	private Session session;
	private static final List<String> PERMISSIONS = Arrays
			.asList("publish_actions");
	private static final String PENDING_PUBLISH_KEY = "pendingPublishReauthorization";
	private boolean pendingPublishReauthorization = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.postfacebook_layout);

		// connect facebook function
		this.session = createSession();
		Settings.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);
		Settings.addLoggingBehavior(LoggingBehavior.INCLUDE_RAW_RESPONSES);
		Settings.addLoggingBehavior(LoggingBehavior.DEVELOPER_ERRORS);
		// /

		initView();
		getExtra();
		loadImage();
	}

	private void initView() {
		card1 = (ImageView) findViewById(R.id.img_card1_save);
		card2 = (ImageView) findViewById(R.id.img_card2_save);
		card3 = (ImageView) findViewById(R.id.img_card3_save);
		card4 = (ImageView) findViewById(R.id.img_card4_save);
		card1.setClickable(false);
		card2.setClickable(false);
		card3.setClickable(false);
		card4.setClickable(false);
		btn_back = (ImageView) findViewById(R.id.btnBack_postfacebook);
		btn_help = (ImageView) findViewById(R.id.btnhelp_postfacebook);
		edit_status = (EditText) findViewById(R.id.edit_postfacebook);
		btn_share = (ImageView) findViewById(R.id.btn_postfacebook);
		bg_layout = (ImageView) findViewById(R.id.img_bg_postfacebook);
		wait_layout = (LinearLayout) findViewById(R.id.layout_wait);
		jumpCard = (ImageView) findViewById(R.id.img_jump_card1_save);
		btn_share.setOnClickListener(this);
		btn_back.setOnClickListener(this);
		btn_help.setOnClickListener(this);
	}

	void getExtra() {
		Intent intent = getIntent();
		Bundle bundle = intent.getExtras();
		deckId = bundle.getInt("deckId");
		number_of_card = bundle.getInt("number_of_card");
		cardBean1 = bundle.getParcelable("cardBean1");
		cardBean2 = bundle.getParcelable("cardBean2");
		cardBean3 = bundle.getParcelable("cardBean3");
		cardBean4 = bundle.getParcelable("cardBean4");
	}

	private Handler handlerLoadImage = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				card1.setImageDrawable((Drawable) msg.obj);
				break;
			case 2:
				card2.setImageDrawable((Drawable) msg.obj);
				break;
			case 3:
				card3.setImageDrawable((Drawable) msg.obj);
				break;
			case 4:
				card4.setImageDrawable((Drawable) msg.obj);
				break;
			case 5:
				bg_layout.setBackgroundDrawable((Drawable) msg.obj);
				break;
			default:
				break;
			}
		};
	};

	void loadImage() {
		if (deckId == 999) {
			bg_layout.setImageResource(R.drawable.bg999);
		} else
			// Load BackGround image
			new ThreadLoadImage(this, handlerLoadImage,
					ConstantValue.getPatchCardData(this) + "Card_"
							+ convertIdToStringId(deckId) + "/en_bg"
							+ convertIdToStringId(deckId) + ".jpg", bg_layout,
					5).start();

		// load card1
		loadCard1();
		// Load card 2,3,4
		switch (number_of_card) {
		case 3:
			loadCard2();
			loadCard3();
			break;
		case 4:
			loadCard2();
			loadCard3();
			loadCard4();
			break;

		default:
			break;
		}
		// Load Jump Card
		findViewById(R.id.img_jump_card1_save).setVisibility(
				cardBean1.isJump ? View.VISIBLE : View.INVISIBLE);
		findViewById(R.id.img_jump_card2_save).setVisibility(
				cardBean2.isJump ? View.VISIBLE : View.INVISIBLE);
		findViewById(R.id.img_jump_card3_save).setVisibility(
				cardBean3.isJump ? View.VISIBLE : View.INVISIBLE);
		findViewById(R.id.img_jump_card4_save).setVisibility(
				cardBean4.isJump ? View.VISIBLE : View.INVISIBLE);
	}

	// Load card1
	void loadCard1() {
		new ThreadLoadImage(this, handlerLoadImage,
				getCardPatchByCardId(cardBean1), card1, 1).start();
	}

	void loadCard2() {
		new ThreadLoadImage(this, handlerLoadImage,
				getCardPatchByCardId(cardBean2), card2, 2).start();
		card2.setVisibility(View.VISIBLE);
	}

	void loadCard3() {
		new ThreadLoadImage(this, handlerLoadImage,
				getCardPatchByCardId(cardBean3), card3, 3).start();
		card3.setVisibility(View.VISIBLE);
	}

	void loadCard4() {
		new ThreadLoadImage(this, handlerLoadImage,
				getCardPatchByCardId(cardBean4), card4, 4).start();
		card4.setVisibility(View.VISIBLE);
	}

	String getCardPatchByCardId(CardBean cardBean) {
		return ConstantValue.getPatchCardData(this) + "Card_"
				+ convertIdToStringId(cardBean.deckId) + "/X3/en_c"
				+ convertIdToStringId(cardBean.deckId)
				+ convertIdToStringId(cardBean.cardId) + ".png";
	}

	String convertIdToStringId(int id) {
		return id < 10 ? "0" + id : "" + id;
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.btn_postfacebook:
			KeyboardHelper.hideSoftKeyboard(this);
			String status = edit_status.getText().toString();
			if (status.matches("")) {
				showDialogCancelPost();
				return;
			}
			if (NetworkUtils.isNetworkConnected(this)) {

				if (this.session.isOpened()) {
					postToFacebook();
				} else {
					this.session = createSession();
					StatusCallback callback = new StatusCallback() {
						public void call(Session session, SessionState state,
								Exception exception) {
							if (state.isOpened()) {
								postToFacebook();
							} else {
								if (state.isClosed()) {
									Log.e("StatusCallback", session.toString());
								}

							}
						}
					};
					this.session
							.openForPublish(new Session.OpenRequest(this)
									.setCallback(callback)
									.setPermissions(PERMISSIONS)
									.setLoginBehavior(
											SessionLoginBehavior.SUPPRESS_SSO));
				}
			} else {
				showDialogSetting();
			}
			break;
		case R.id.btnBack_postfacebook:

			if (postBitmap != null) {
				postBitmap.recycle();
			}
			setResult(RESULT_CANCELED);
			finish();
			break;
		case R.id.btnhelp_postfacebook:
			Intent intent = new Intent(this, HelpActivity.class);
			intent.putExtra(HelpActivity.KEY_HELP_INDEX, 11);
			startActivityForResult(intent, 0);
			overridePendingTransition(R.anim.slide_in_right,
					R.anim.slide_out_left);
			break;
		default:
			break;
		}

	}

	void gotoCardDetail(CardBean cardBean) {
		Intent intent = new Intent(this, CardDetailActivity.class);
		intent.putExtra("deckId", cardBean.deckId);
		intent.putExtra("cardId", cardBean.cardId);
		startActivityForResult(intent, ConstantValue.SAVE_HISTORY_ACTIVITY);
		overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
	}

	/**
	 * Lấy phiên kết nối của facebook
	 * 
	 * @return
	 */
	private Session createSession() {
		Session activeSession = Session.getActiveSession();
		if (activeSession == null || activeSession.getState().isClosed()) {
			activeSession = new Session.Builder(this).setApplicationId(
					this.getResources().getString(R.string.app_id)).build();
			Session.setActiveSession(activeSession);
		}
		return activeSession;
	}

	void showDialogCancelPost() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		// Creates textview for centre title
		TextView txtTitle = new TextView(this);
		txtTitle.setGravity(Gravity.CENTER);
		txtTitle.setTextColor(Color.WHITE);
		txtTitle.setText("Error");
		txtTitle.setTextSize(20);
		builder.setCustomTitle(txtTitle);
		builder.setMessage("Please input some caption for image");
		builder.setNegativeButton("OK", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
				dialog.dismiss();
			}
		});
		builder.show();
	}

	/**
	 * post history lên facebook
	 */
	private void postToFacebook() {
		if (session != null) {

			// Check for publish permissions
			List<String> permissions = session.getPermissions();
			if (!isSubsetOf(PERMISSIONS, permissions)) {
				pendingPublishReauthorization = true;
				Session.NewPermissionsRequest newPermissionsRequest = new Session.NewPermissionsRequest(
						this, PERMISSIONS);
				session.requestNewPublishPermissions(newPermissionsRequest);
				return;
			}

			Request.Callback postPhotoCallback = new Request.Callback() {

				@Override
				public void onCompleted(Response response) {
					// TODO Auto-generated method stub
					Log.e("postToFacebook", response.toString());
					if (response.getError() == null) {
						// Tell the user success!
						Toast.makeText(getApplicationContext(), "Success",
								Toast.LENGTH_SHORT).show();
					} else {
						Toast.makeText(getApplicationContext(), "Error",
								Toast.LENGTH_SHORT).show();
					}
					setWaitScreen(false);
				}

			};

			setWaitScreen(true);

			if (postBitmap == null) {
				postBitmap = createPostImage();
			}

			Request postPhoto = Request.newUploadPhotoRequest(session,
					postBitmap, postPhotoCallback);
			Bundle params = postPhoto.getParameters();
			params.putString("message", edit_status.getText().toString());
			postPhoto.executeAsync();

		}

	}

	/**
	 * kiểm tra quyền login facebook
	 * 
	 * @param subset
	 * @param superset
	 * @return
	 */
	private boolean isSubsetOf(Collection<String> subset,
			Collection<String> superset) {
		for (String string : subset) {
			if (!superset.contains(string)) {
				return false;
			}
		}
		return true;
	}

	private static final int IMAGE_SPACE = 15;

	private Bitmap createPostImage() {

		if (number_of_card >= 1) {

			int itemWidth = ((BitmapDrawable) card1.getDrawable()).getBitmap()
					.getWidth();
			int itemHeight = ((BitmapDrawable) card1.getDrawable()).getBitmap()
					.getHeight();
			int bitmapWidth = itemWidth * number_of_card + IMAGE_SPACE
					* (number_of_card + 1);

			Bitmap postBitmap = Bitmap.createBitmap(bitmapWidth, itemHeight
					+ IMAGE_SPACE, Bitmap.Config.RGB_565);
			Canvas canvas = new Canvas(postBitmap);
			Paint paint = new Paint();
			paint.setAntiAlias(true);
			paint.setDither(true);

			canvas.drawColor(Color.WHITE);
			if (number_of_card == 1) {
				canvas.drawBitmap(
						((BitmapDrawable) card1.getDrawable()).getBitmap(),
						IMAGE_SPACE, 0, paint);
			} else if (number_of_card == 2) {
				canvas.drawBitmap(
						((BitmapDrawable) card1.getDrawable()).getBitmap(),
						IMAGE_SPACE, 0, paint);
				canvas.drawBitmap(
						((BitmapDrawable) card2.getDrawable()).getBitmap(),
						itemWidth + IMAGE_SPACE + IMAGE_SPACE, 0, paint);
			} else if (number_of_card == 3) {
				canvas.drawBitmap(
						((BitmapDrawable) card1.getDrawable()).getBitmap(),
						IMAGE_SPACE, 0, paint);
				canvas.drawBitmap(
						((BitmapDrawable) card2.getDrawable()).getBitmap(),
						itemWidth + IMAGE_SPACE + IMAGE_SPACE, 0, paint);
				canvas.drawBitmap(
						((BitmapDrawable) card3.getDrawable()).getBitmap(),
						itemWidth + itemWidth + IMAGE_SPACE + IMAGE_SPACE
								+ IMAGE_SPACE, 0, paint);
			} else if (number_of_card == 4) {
				canvas.drawBitmap(
						((BitmapDrawable) card1.getDrawable()).getBitmap(),
						IMAGE_SPACE, 0, paint);
				canvas.drawBitmap(
						((BitmapDrawable) card2.getDrawable()).getBitmap(),
						itemWidth + IMAGE_SPACE + IMAGE_SPACE, 0, paint);
				canvas.drawBitmap(
						((BitmapDrawable) card3.getDrawable()).getBitmap(),
						itemWidth + itemWidth + IMAGE_SPACE + IMAGE_SPACE
								+ IMAGE_SPACE, 0, paint);
				canvas.drawBitmap(
						((BitmapDrawable) card4.getDrawable()).getBitmap(),
						itemWidth + itemWidth + itemWidth + IMAGE_SPACE
								+ IMAGE_SPACE + IMAGE_SPACE + IMAGE_SPACE, 0,
						paint);
			}

			if (cardBean1.isJump) {
				canvas.drawBitmap(
						((BitmapDrawable) jumpCard.getDrawable()).getBitmap(),
						0, 0, paint);
			}
			if (cardBean2.isJump && number_of_card > 1) {
				canvas.drawBitmap(
						((BitmapDrawable) jumpCard.getDrawable()).getBitmap(),
						itemWidth + IMAGE_SPACE, 0, paint);
			}
			if (cardBean3.isJump && number_of_card > 2) {
				canvas.drawBitmap(
						((BitmapDrawable) jumpCard.getDrawable()).getBitmap(),
						itemWidth + itemWidth + IMAGE_SPACE + IMAGE_SPACE, 0,
						paint);
			}
			if (cardBean4.isJump && number_of_card > 3) {
				canvas.drawBitmap(
						((BitmapDrawable) jumpCard.getDrawable()).getBitmap(),
						itemWidth + itemWidth + itemWidth + IMAGE_SPACE
								+ IMAGE_SPACE + IMAGE_SPACE, 0, paint);
			}

			return postBitmap;

		} else {
			return null;
		}

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
		Session.getActiveSession().onActivityResult(this, requestCode,
				resultCode, data);
	}

	// Tắt/bật màn hình chờ
	void setWaitScreen(boolean set) {
		wait_layout.setVisibility(set ? View.VISIBLE : View.GONE);
		edit_status.setEnabled(set ? false : true);
		btn_back.setClickable(set ? false : true);
		btn_help.setClickable(set ? false : true);
		btn_share.setClickable(set ? false : true);
	}

	void showDialogSetting() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		// Creates textview for centre title
		TextView myMsg = new TextView(this);
		myMsg.setText("No internet connection");
		myMsg.setGravity(Gravity.CENTER_HORIZONTAL);
		myMsg.setTextSize(20);
		myMsg.setTextColor(Color.WHITE);
		// set custom title
		builder.setCustomTitle(myMsg);
		builder.setMessage("Please check your setting network");
		builder.setNegativeButton("OK", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
				dialog.dismiss();
			}
		});
		builder.setPositiveButton("Setting",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						dialog.dismiss();
						startActivity(new Intent(
								android.provider.Settings.ACTION_SETTINGS));
					}
				});
		AlertDialog dialog = builder.show();
	}

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
		if (postBitmap != null) {
			postBitmap.recycle();
		}
		super.onBackPressed();
	}

}
